package com.vict.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Optional;
import java.util.Random;

/**
 * ID生成器工具类
 *
 * @author ruoyi
 */
@Component
public class IdUtils {
    @Value("${idutil.workid:}")
    private String workid;

    @Value("${idutil.datacenterId:}")
    private String datacenterId;

    private static Snowflake snowflake;

    @PostConstruct
    public void init(){
        Integer workidInt = Optional.ofNullable(this.workid).map(o -> o.trim()).filter(o-> !o.equals("")).map(o -> Integer.parseInt(o)).orElse(0);
        Integer datacenterIdInt = Optional.ofNullable(this.datacenterId).map(o -> o.trim()).filter(o-> !o.equals("")).map(o -> Integer.parseInt(o)).orElse(0);
        IdUtils.snowflake = IdUtil.getSnowflake(workidInt, datacenterIdInt);
    }

    /**
     * 获取longid
     */
    public static long snowflakeId(){
        return IdUtils.snowflake.nextId();
    }



    /**
     * 生成salt的静态方法
     *
     * @param n 位数
     */
    public static String getSalt(int n) {
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }
}
